﻿using Lzkj.AepCoapCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.Win32;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using XC.Keys;
using Xc.DataAccess.AepCoapCore.Models;
using Xc.DataAccess.Core;
using Xc.Logics.AepCoap;
using Xc.Logics.AepCoap.Services;
using System.Collections.ObjectModel;
using System.ComponentModel;
using DotNetUI.Controls;
using Xc.Views.Booster.Views;
using Xc.DataAccess.Core.Services;

namespace Xc.Logics.AepCoap.Views
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainView : UserControl
    {
        private readonly IAepCoapService aepCoapService;
        private readonly IServiceProvider serviceProvider;
        private readonly ICsvService csvService;
        private readonly IAepUploadService aepUploadService;
        private readonly IOptions<AppSetting> options;
        public MainView(IAepCoapService aepCoapService, IServiceProvider serviceProvider, ICsvService csvService, IOptions<AppSetting> options, IAepUploadService aepUploadService)
        {
            InitializeComponent();
            this.aepCoapService = aepCoapService;
            this.serviceProvider = serviceProvider;
            this.csvService = csvService;
            this.options = options;
            this.aepUploadService = aepUploadService;
            txbblock.DataContext = this;
        }



        private async void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            await RefreshAsync();
        }

        private async void dxgDeviceList_Loaded(object sender, RoutedEventArgs e)
        {

            //await RefreshAsync();
        }


        private async Task RefreshAsync()
        {
            if (ViewModel.DeviceInfoLists.Count > 0)
            {
                ViewModel.DeviceInfoLists.Clear();
            }
            await Task.Run(async () =>
            {
                var res = await aepCoapService.QueryDeviceList(new QueryDeviceList { AppKey = options.Value.AepInfo.AppKey, AppSecret = options.Value.AepInfo.AppSecret, MasterKey = options.Value.AepInfo.MasterKey, ProductId = options.Value.AepInfo.ProductId, PageNow = 1, PageSize = 500, SearchValue = "" });
                if (res.IsSuccess)
                {
                    if (res.Data.Code == 0 && res.Data.Result != null)
                    {
                        var total = res.Data.Result.Total;
                        this.ViewModel.DeviceInfoCount = total;
                        var count = total / 100;
                        var yu = total % 100;
                        if (yu > 0)
                        {
                            count++;
                        }
                        for (int i = 1; i <= count; i++)
                        {
                            var res1 = await aepCoapService.QueryDeviceList(new QueryDeviceList { AppKey = options.Value.AepInfo.AppKey, AppSecret = options.Value.AepInfo.AppSecret, MasterKey = options.Value.AepInfo.MasterKey, ProductId = options.Value.AepInfo.ProductId, PageNow = i, PageSize = 100, SearchValue = "" });
                            if (res1 != null)
                            {
                                if (res1.Data.Code == 0)
                                {
                                    var list = res1.Data.Result.list;

                                    foreach (var item in list)
                                    {
                                        await this.Dispatcher.InvokeAsync(() =>
                                        {
                                            ViewModel.DeviceInfoLists.Add(item);
                                        });
                                    }
                                    await Task.Delay(10);
                                }
                            }
                        }

                    }
                }
            });

        }
 
        private async Task InitDeviceList(string filename)
        {
 
            var lists = await File.ReadAllLinesAsync(filename, Encoding.UTF8);
            if (lists.Count() > 0)
            {
                var buffers = lists.Skip(1).ToList();
                foreach (var item in buffers)
                {
                    AddDeviceModel model = new AddDeviceModel();
                    try
                    {
                        string[] vs = item.Split(',');
                        for (int i = 0; i < vs.Length; i++)
                        {
                            if (vs.Length == 3)
                            {
                                MessageBox.Show($"错误的设备，无法注册,第{i}行", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                                continue;
                            }

                            if (vs.Length >= 4)
                            {
                                model.DeviceNumber = StrReplce(vs[1]);
                                model.ProductTime = StrReplce(vs[0]);
                                model.IMEI = StrReplce(vs[2]);

                                model.IMSI = StrReplce(vs[3]);
                                if (model.IMSI.Length!=15)
                                {
                                    model.IMSI = string.Empty;
                                }
                            }
                            else
                            {
                                model.IMSI = String.Empty;
                                continue;
                            }
                        }
                        if (!string.IsNullOrEmpty(model.IMEI)&&model.Plantform==Plantform.电信)
                        {
                            ViewModel.ImportDevices.Add(model);
                        }
                    }
                    catch (Exception err)
                    {

                    }

                }
            }
        }

        private string StrReplce(string str)
        {
            string aa = str.Replace("'", "");
            return aa;
        }

        private async void filecsv_ItemClick(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Windows.Forms.FolderBrowserDialog folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
                if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                  var files=   Directory.EnumerateFiles(folderBrowserDialog.SelectedPath,"*.csv", SearchOption.AllDirectories);
                    filename.Content = folderBrowserDialog.SelectedPath;
                    if (ViewModel.ImportDevices.Count() > 0)
                    {
                        ViewModel.ImportDevices.Clear();
                    }
                    foreach (var item in files)
                    {
                        await InitDeviceList(item);
                    }
                    ViewModel.ImportDevices = new ObservableCollection<AddDeviceModel>(ViewModel.ImportDevices.OrderByDescending(p => p.CreateTime).GroupBy(g => g.IMEI).Select(p => p.FirstOrDefault()));
                    dxg.ItemsSource = ViewModel.ImportDevices;


                }
            }
            catch (Exception err)
            {
                MessageBox.Show("请检查文件是否已打开，若打开请关闭" + err.Message);
            }

        }

        private void BarButtonItem_ItemClick(object sender, RoutedEventArgs e)
        {
            serviceProvider.GetDotNetWindowService<SettingView>().SetTitle("参数配置").SetWindowStartupLocation(WindowStartupLocation.CenterScreen).SetSizePercent(0.6).ShowDialog();
        }

        private void BarButtonItem_ItemClick_1(object sender, RoutedEventArgs e)
        {
            serviceProvider.GetDotNetWindowService<LogView>().SetTitle("操作说明").SetSizePercent(0.5).SetSizeToContent(SizeToContent.Height).SetWindowStartupLocation(WindowStartupLocation.CenterScreen).SetResizeMode(ResizeMode.NoResize).ShowDialog();
        }
        private async void AddDevice_Click(object sender, RoutedEventArgs e)
        {
            await aepUploadService.UploadAsync(ck.IsChecked == true, ViewModel.ImportDevices, (result) =>
              {
                  ToCsvFile(result.DateTime.ToFullString(), result.DeviceNumber, result.IMEI, result.IMSI, result.Message);
              }, ViewModel.DeviceInfoLists);
            if (ViewModel.ImportDevices.Count() > 0)
            {

              //  await RefreshAsync();
            }
            else
            {
                MessageBox.Show("请先加载文件");
            }
        }

        public Result ToCsvFile(params string[] content)
        {
            var path = AppDomain.CurrentDomain.BaseDirectory + "Data\\";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            var strfile = DateTime.Now.ToString("yyyyMMdd") + "_设备新增(修改)明细表.csv";
            var filename = path + strfile;
            return csvService.WriteToFile(filename, new List<string[]> { content }, "设备注册日期", "设备名称", "IMEI号", "IMSI号", "描述信息");
        }

        private void ThemedWindow_Loaded(object sender, RoutedEventArgs e)
        {
            
        }



        private void dxg_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = e.Row.GetIndex() + 1;
        }

        private async void dxg_Loaded(object sender, RoutedEventArgs e)
        {
            //await RefreshAsync();
        }


        private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (dxgDeviceList != null && dxgDeviceList.SelectedItem != null)
            {
                e.CanExecute = true;
            }
            else
            {
                e.CanExecute = false;
            }
        }

        private async void CommandBinding_Executed_1(object sender, ExecutedRoutedEventArgs e)
        {
            if (dxgDeviceList.SelectedItem is DeviceInfoList device)
            {
                if (MessageBox.Show("确定要删除设备吗？","提示",MessageBoxButton.YesNo,MessageBoxImage.Question)==MessageBoxResult.Yes)
                {
                    aepUploadService.DeleteAsync(new DeleteDevice { AppKey = options.Value.AepInfo.AppKey, AppSecret = options.Value.AepInfo.AppSecret, MasterKey = options.Value.AepInfo.MasterKey, ProductId = options.Value.AepInfo.ProductId, DevcieIds = device.DeviceId });
                    await RefreshAsync();
                }

            }
        }

        private async void DotNetButton_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("确定要批量删除吗？","提示",MessageBoxButton.YesNo,MessageBoxImage.Question)==MessageBoxResult.Yes)
            {
                try
                {
                    Queue<string> models = new Queue<string>();
                    ViewModel.Index = 0;
                    this.ViewModel.Visibility = Visibility.Visible;
                    foreach (var item in ViewModel.ImportDevices)
                    {
                        var dev = ViewModel.DeviceInfoLists.Where(p => p.IMEI == item.IMEI).FirstOrDefault();
                        if (dev != null)
                        {
                            var c = await Task.Run(() => { return aepUploadService.DeleteAsync(new DeleteDevice { AppKey = options.Value.AepInfo.AppKey, AppSecret = options.Value.AepInfo.AppSecret, MasterKey = options.Value.AepInfo.MasterKey, ProductId = options.Value.AepInfo.ProductId, DevcieIds = dev.DeviceId }); });
                            if (c.IsSuccess)
                            {
                                models.Enqueue(item.IMEI);
                                item.AddDeviceStatus = "删除成功";
                            }
                            else
                            {
                                item.AddDeviceStatus = c.Message;
                            }
                        }
                        ViewModel.Index++;
                    }
                    while (models.TryDequeue(out var item))
                    {
                        var dev = ViewModel.ImportDevices.Where(p => p.IMEI == item).FirstOrDefault();
                        if (dev != null)
                        {
                            ViewModel.ImportDevices.Remove(dev);
                        }

                    }
                    this.ViewModel.Visibility = Visibility.Collapsed;
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.Message,"错误");
                }
                finally
                {
                    ViewModel.Index = 0;
                    this.ViewModel.Visibility = Visibility.Collapsed;
                }
            }
        }

        private void DotNetButton_Click_1(object sender, RoutedEventArgs e)
        {
            dxg.ItemsSource = ViewModel.ImportDevices;

        }
    }
}
